package com.walkline.screen;

import java.util.Hashtable;

import net.rim.device.api.system.Characters;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.BackgroundFactory;
import net.rim.device.api.ui.picker.FilePicker;
import net.rim.device.api.util.StringProvider;

import com.walkline.util.Enumerations.RefreshAction;
import com.walkline.util.Function;
import com.walkline.util.ImageItem;
import com.walkline.util.StringUtility;
import com.walkline.util.container.ForegroundManager;
import com.walkline.util.ui.MyTextField;
import com.walkline.weibo.WeiboException;
import com.walkline.weibo.WeiboSDK;
import com.walkline.weibo.inf.Status;

public class NewStatusMainScreen extends MainScreen implements FilePicker.Listener
{
	WeiboSDK _weibo;
	ForegroundManager _foreground = new ForegroundManager(0);
	ShowEmotionPopupScreen emotionScreen = new ShowEmotionPopupScreen();

	MyTextField _statusField = new MyTextField();
	BitmapField[] _bitmapField = new BitmapField[9];// = new BitmapField();
	FilePicker _filePicker;
	ImageItem[] _imageItem = new ImageItem[9];
	int _currentImageCount = 0;

	public NewStatusMainScreen(WeiboSDK weibo)
	{
		super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

		_weibo = weibo;

        _filePicker = FilePicker.getInstance();
        _filePicker.setTitle("Choose file");
        if (!DeviceInfo.isSimulator()) {_filePicker.setView(FilePicker.VIEW_PICTURES);}
        _filePicker.setFilter(".png:.gif:.jpg");

		HorizontalFieldManager hfm=new HorizontalFieldManager(FIELD_HCENTER);
		hfm.add(new LabelField("发表微博"));
		setTitle(hfm);

		_statusField.setMaxSize(200);
		_statusField.setPadding(3, 3, 3, 3);
		_statusField.setMargin(10, 3, 3, 3);

		ButtonField updateButton = new ButtonField("发送文字", ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
		updateButton.setChangeListener(new FieldChangeListener()
		{
			public void fieldChanged(Field field, int context)
			{
				String newText = _statusField.getText();

				if (StringUtility.getUnicodeLength(newText) > 140)
				{
					Function.errorDialog("内容超出字数限制，不要超过140字");
					_statusField.setFocus();

					return;
				}

				if (newText.trim().equals(""))
				{
					Function.errorDialog("微博内容不能为空");
					_statusField.setFocus();

					return;
				}

				if (updateStatus(newText))
				{
					Function.errorDialog("发送成功！");
					onClose();
				} else {
					Function.errorDialog("发送失败！");
				}
			}
		});
		updateButton.setMargin(5, 5, 5, 10);

		ButtonField uploadButton = new ButtonField("发送图文", ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
		uploadButton.setChangeListener(new FieldChangeListener()
		{
			public void fieldChanged(Field field, int context)
			{
				String newText = _statusField.getText();

				if (StringUtility.getUnicodeLength(newText) > 140)
				{
					Function.errorDialog("内容超出字数限制，不要超过140字");
					_statusField.setFocus();

					return;
				}

				if (newText.trim().equals(""))
				{
					Function.errorDialog("微博内容不能为空");
					_statusField.setFocus();

					return;
				}

				if (uploadStatus(newText))
				{
					Function.errorDialog("发送成功！");
					onClose();
				} else {
					Function.errorDialog("发送失败！");
				}
			}
		});
		uploadButton.setMargin(5, 5, 5, 10);

		ButtonField addImage = new ButtonField("添加图片", ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
		addImage.setChangeListener(new FieldChangeListener()
		{
			public void fieldChanged(Field field, int context)
			{
				_filePicker.show();
			}
		});
		addImage.setMargin(5, 5, 5, 0);

		HorizontalFieldManager hfmImage = new HorizontalFieldManager(FIELD_HCENTER);
		VerticalFieldManager vfmImage = new VerticalFieldManager();
		for (int i=0; i<9; i++)
		{
			_bitmapField[i] = new BitmapField();
			vfmImage.add(_bitmapField[i]);
		}
		hfmImage.add(vfmImage);

		_foreground.setBackground(BackgroundFactory.createSolidBackground(Color.BLACK));
		_foreground.add(_statusField);
		_foreground.add(updateButton);
		_foreground.add(uploadButton);
		_foreground.add(addImage);
		_foreground.add(hfmImage);

		add(_foreground);

		_filePicker.setListener(this);
	}

	/**
	 * 发送一条文字微博
	 */
	private boolean updateStatus(String text)
	{
		RefreshContentsScreen popupScreen = new RefreshContentsScreen(_weibo, text, RefreshAction.SENDTEXTSTATUS);
		UiApplication.getUiApplication().pushModalScreen(popupScreen);

		Status status = popupScreen.getStatus();

		if (popupScreen != null) {popupScreen = null;}

		return status != null;
	}

	/**
	 * 上传图片并发送一条微博
	 */
	private boolean uploadStatus(String text)
	{
		Hashtable params = new Hashtable();

		params.put("status", text);
		params.put("images", _imageItem);

		RefreshContentsScreen popupScreen = new RefreshContentsScreen(_weibo, params, RefreshAction.SENDIMAGESTATUS);
		UiApplication.getUiApplication().pushModalScreen(popupScreen);

		Status status = popupScreen.getStatus();

		if (popupScreen != null) {popupScreen = null;}

		return status != null;
	}

	/**
	 * 获取一个@用户时的联想建议
	 */
	private void getSuggestionUser()
	{
		SuggestionUserPopupScreen popupScreen = new SuggestionUserPopupScreen(_weibo);
		UiApplication.getUiApplication().pushModalScreen(popupScreen);

		_statusField.insert(popupScreen.getSuggestUser());
	}

	/**
	 * 获取一个表情符号
	 */
	private void getEmotion()
	{
		UiApplication.getUiApplication().pushModalScreen(emotionScreen);

		_statusField.insert(emotionScreen.getEmotion());
	}

	protected boolean keyDown(int keycode, int time)
	{
		if (_statusField.isFocus())
		{
			if (keycode == 8323073) //alt + sym
			{
				getEmotion();
				return true;
			} else if (keycode == 5242881) { //alt + p
				_statusField.backspace(1);
				getSuggestionUser();
				return true;
			//} else {
				//Function.errorDialog("keycode: " + keycode);
			}
		}

		return super.keyDown(keycode, time);
	}

	protected boolean keyChar(char key, int status, int time)
	{
		if (_statusField.isFocus())
		{
			switch (key)
			{
				case Characters.COMMERCIAL_AT:
					getSuggestionUser();
					return true;
			}
		}

		return super.keyChar(key, status, time);
	}

	MenuItem menuSend = new MenuItem(new StringProvider("发送"), 100, 10)
	{
		public void run()
		{
			
		}
	};

	MenuItem menuInsertTag = new MenuItem(new StringProvider("插入标签"), 100, 20)
	{
		public void run()
		{
			_statusField.setText("#AnotherWeibo# " + _statusField.getText());
		}
	};

	MenuItem menuInsertEmotion = new MenuItem(new StringProvider("插入表情(alt+sym)"), 100, 30)
	{
		public void run() {getEmotion();}
	};

	protected void makeMenu(Menu menu, int instance)
    {
    	menu.add(menuInsertTag);
    	menu.add(menuInsertEmotion);
    	menu.addSeparator();

    	super.makeMenu(menu, instance);
    }

	protected boolean onSavePrompt() {return true;}

	public void selectionDone(String selected)
	{
		if (selected != null && selected.length() > 0)
		{
			try {
				_imageItem[_currentImageCount] = new ImageItem(selected);

				if (_imageItem[_currentImageCount] != null)
				{
					EncodedImage image = EncodedImage.createEncodedImage(_imageItem[_currentImageCount].getContent(), 0, _imageItem[_currentImageCount].getContent().length);

					_bitmapField[_currentImageCount].setBitmap(Function.bestFit(image, 200, 200));
				}

				_currentImageCount += 1;
			} catch (WeiboException e) {Function.errorDialog(e.toString());}	
		} else {
			_bitmapField[_currentImageCount].setBitmap(null); 
		}
	}
}